package com.hntx.joymusic.web;

import android.content.Intent;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.utils.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.hntx.joymusic.R;
import com.hntx.joymusic.adapter.MyListAdapter;
import com.hntx.joymusic.bean.VideoBean;
import com.hntx.joymusic.mediaplayer.StringUtils;
import com.hntx.joymusic.mediaplayer.TrackBean;
import com.hntx.joymusic.view.CenterRecyclerView;
import com.hntx.joymusic.view.focus.RecyclerViewSpacesItemDecoration;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;

import tv.danmaku.ijk.media.player.IMediaPlayer;
import tv.danmaku.ijk.media.player.IjkMediaPlayer;
import tv.danmaku.ijk.media.player.misc.ITrackInfo;
import tv.danmaku.ijk.media.player.misc.IjkTrackInfo;


public class IjkVideoActivity extends AppCompatActivity
        implements SurfaceHolder.Callback, View.OnClickListener,
        SeekBar.OnSeekBarChangeListener, MyListAdapter.OnRightFocusChangeListener,
        MyListAdapter.OnRightClickListener,
        ViewTreeObserver.OnGlobalLayoutListener {
    private String TAG = "IjkVideoActivity";
    private SurfaceView mPlayerView;
    private SeekBar seekBar;
    private RelativeLayout updateProgressBar;
    private ImageButton btn_play_pause;
    private TextView musicName, tv_time_total, tv_time_current, subtitle_text,
            seek_to_time, nextName, musicAuthor;
    private RelativeLayout playerControlBottomLayout;
    private ImageView paly_btn, load_img, forwardLeft, forwardRight,
            musicImg, musicCollect, origLyrics, musicReplay, musicNext, playMode, musicList;

    private long videoDuration;
    private String mName = null, authName = null, nextNameStr = null;
    private List<VideoBean> videoBeanList = new ArrayList<>();
    private String userId;
    private String firstUrl = null;
    private int startPosition;
    private int nextPosition = 0;

    private Timer timer;
    private TimerTask timerTask;
    private List<TrackBean> audioList = null;
    private int audioSelIndex = -1;
    private int PLAY_MODE = 1;//顺序播放 1，单曲循环 2,随机播放 3

    private CenterRecyclerView recycler;
    private MyListAdapter listAdapter;
    private LinearLayoutManager layoutManager;

    IjkMediaPlayer player;
    SurfaceHolder surfaceHolder;
    private Handler mHandler = new MyHandler(this);
    private static final int HIDE = 1, SHOW = 2, FINISH = 3, ENABLE_SEEK = 4,
            ENABLE_PLAY = 5, SEEK_VIEW_HIDE = 9;
    private int timeout = 5000;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        getTestData();
        getIntentData();
    }

    List<String> allPath = new ArrayList<>();

    private void getTestData() {
        File file = new File("mnt/usb/sda1/musics/");
        File fileSda = new File("mnt/sda/sda1/musics/");
        if (file.exists()) {
            File[] files = file.listFiles();
            if (files.length > 0)
                for (int i = 0; i < files.length; i++) {
                    allPath.add("file:///mnt/usb/sda1/musics/" + files[i].getName());
                    Log.d("显示文件：", files[i].getName());
                }
        } else if (fileSda.exists()) {
            File[] files = fileSda.listFiles();
            if (files.length > 0)
                for (int i = 0; i < files.length; i++) {
                    allPath.add("file:///mnt/sda/sda1/musics/" + files[i].getName());
                    Log.d("显示文件：", files[i].getName());
                }
        }
    }

    private void getIntentData() {
        setContentView(R.layout.activity_first_video);
        initView();
        getInit();
        initData();
        initPlayer();
    }

    private void getInit() {
        videoBeanList = getIntent().getParcelableArrayListExtra("video_bean_list");
        startPosition = getIntent().getIntExtra("start_position", 0);
//        startTime = getIntent().getIntExtra("startTime", 0);
        firstUrl = getIntent().getStringExtra("firstUrl");
        firstUrl = allPath.get(0);
        userId = getIntent().getStringExtra("userId");
        if (videoBeanList != null)
            if (videoBeanList.size() > 0 && videoBeanList.size() > startPosition) {
                mName = videoBeanList.get(startPosition).getSongName();
                authName = videoBeanList.get(startPosition).getSinger();
                nextPosition = startPosition + 1;
                if (videoBeanList.size() > 1)
                    nextNameStr = videoBeanList.get(nextPosition).getSongName();
                else
                    nextNameStr = videoBeanList.get(startPosition).getSongName();
            }
    }

    private void initView() {
        playerControlBottomLayout = (RelativeLayout) findViewById(R.id.player_control_bottom_layout);
        paly_btn = (ImageView) findViewById(R.id.control_btn);
        seekBar = (SeekBar) findViewById(R.id.seekBar);
        updateProgressBar = (RelativeLayout) findViewById(R.id.update_progress);
        mPlayerView = (SurfaceView) findViewById(R.id.mPlayerView);
        btn_play_pause = (ImageButton) findViewById(R.id.btn_play_pause);
        tv_time_total = (TextView) findViewById(R.id.tv_time_total);
        tv_time_current = (TextView) findViewById(R.id.tv_time_current);
        subtitle_text = (TextView) findViewById(R.id.subtitle_text);
        load_img = (ImageView) findViewById(R.id.load_img);
        seek_to_time = (TextView) findViewById(R.id.seek_to_time);
        seekBar.setOnSeekBarChangeListener(this);
        paly_btn.setOnClickListener(this);

        recycler = (CenterRecyclerView) findViewById(R.id.right_recycler);
        musicName = (TextView) findViewById(R.id.music_name);
        nextName = (TextView) findViewById(R.id.music_next_name);
        musicImg = (ImageView) findViewById(R.id.music_img);
        musicAuthor = (TextView) findViewById(R.id.music_author);
        forwardLeft = (ImageView) findViewById(R.id.forward_left);
        forwardRight = (ImageView) findViewById(R.id.forward_right);
        musicCollect = (ImageView) findViewById(R.id.music_collect);
        origLyrics = (ImageView) findViewById(R.id.orig_lyrics);
        musicReplay = (ImageView) findViewById(R.id.music_replay);
        musicNext = (ImageView) findViewById(R.id.music_next);
        playMode = (ImageView) findViewById(R.id.play_mode);
        musicList = (ImageView) findViewById(R.id.music_list);

        forwardLeft.setOnClickListener(this);
        forwardRight.setOnClickListener(this);
        musicCollect.setOnClickListener(this);
        origLyrics.setOnClickListener(this);
        musicReplay.setOnClickListener(this);
        musicNext.setOnClickListener(this);
        playMode.setOnClickListener(this);
        musicList.setOnClickListener(this);
    }

    private void initData() {
        Animation translateAnimation = AnimationUtils.loadAnimation(this, R.anim.load_anim);
        if (load_img != null) {
            load_img.setAnimation(translateAnimation);
            load_img.startAnimation(translateAnimation);
        }
        listAdapter = new MyListAdapter(this);
        layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        recycler.setLayoutManager(layoutManager);
        recycler.setAdapter(listAdapter);
        listAdapter.addRightFocusChangeListener(this);
        listAdapter.addRightClickListener(this);
        recycler.addItemDecoration(new RecyclerViewSpacesItemDecoration(6));
        listAdapter.setData(videoBeanList);
        recycler.getViewTreeObserver().addOnGlobalLayoutListener(this);
    }

    private void initPlayer() {
        // 初始化播放器
        IjkMediaPlayer.loadLibrariesOnce(null);
        IjkMediaPlayer.native_profileBegin("libijkplayer.so");
        player = new IjkMediaPlayer();
        surfaceHolder = mPlayerView.getHolder();
        surfaceHolder.addCallback(this);
        limitOperate = true;
        openVideo(firstUrl);
    }

    private void initListener() {
        player.setOnInfoListener(new IMediaPlayer.OnInfoListener() {
            @Override
            public boolean onInfo(IMediaPlayer iMediaPlayer, int what, int extra) {
                switch (what) {
                    case IjkMediaPlayer.MEDIA_INFO_BUFFERING_START:
//                        player.isBuffering = true;
                        updateProgressBar.setVisibility(View.VISIBLE);
                        break;
                    case IjkMediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START:
                    case IjkMediaPlayer.MEDIA_INFO_BUFFERING_END:
//                        player.isBuffering = false;
                        updateProgressBar.setVisibility(View.GONE);
                        break;
                }
                return false;
            }
        });
//        player.addOnInfoListener((mp, what, extra) -> {
//
//        });
        player.setOnPreparedListener(mp -> {
//            player.isPrepared = true;
            IjkTrackInfo[] mtInfo = player.getTrackInfo();
            encapsulatedOrbit(mtInfo);
            videoDuration = player.getDuration();
            musicName.setText(mName);
            musicAuthor.setText(authName);
            nextName.setText(nextNameStr);
            RequestOptions options = new RequestOptions()
                    .centerCrop()
                    .placeholder(R.mipmap.default_img)
                    .error(R.mipmap.default_img);
            Glide.with(this).load(videoBeanList.get(startPosition).getPic()).apply(options).into(musicImg);
            seekBar.setMax((int) videoDuration);
            seekBar.setProgress((int) player.getCurrentPosition());
            String time = StringUtils.generateTime(videoDuration);
            tv_time_current.setText("00:00");
            tv_time_total.setText(" / " + time);
//            mHandler.sendMessageDelayed(mHandler.obtainMessage(HIDE), timeout);
            timer = new Timer();
            timerTask = new TimerTask() {
                @Override
                public void run() {
                    if (isTimerTask) {
                        if (timer != null)
                            timer.cancel();
                    }
                    if (player != null) {
                        final long currentPosition = player.getCurrentPosition();
                        seekBar.setProgress((int) currentPosition);
                        IjkVideoActivity.this.runOnUiThread(() -> {
                            String time1 = StringUtils.generateTime(currentPosition);
                            tv_time_current.setText(time1);
                        });
                    }
                }
            };
            timer.schedule(timerTask, 0, 100);
        });
        player.setOnBufferingUpdateListener((mp, percent) -> runOnUiThread(() -> {
            if (videoDuration > 0) {
                seekBar.setSecondaryProgress((int) ((percent / 100.0) * videoDuration));
            }
        }));
        player.setOnCompletionListener(mp -> switchMusic());
        player.setOnErrorListener((mp, what, extra) -> {
            Log.d(TAG, "视频播放出错，原因：" + what + "=" + extra);
            return false;
        });
    }

    public void openVideo(String url) {
        try {
            if (player == null) {
                player = new IjkMediaPlayer();
            }
            player.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "fflags", "fastseek");
            player.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "framedrop", 5);
            player.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec_mpeg4", 1);
//            player.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "enable-accurate-seek", 1);
            initListener();
            if (mPlayerView.getVisibility() != View.VISIBLE)
                mPlayerView.setVisibility(View.VISIBLE);
            player.setDataSource(url);
            player.setAudioStreamType(AudioManager.STREAM_MUSIC);
            player.setScreenOnWhilePlaying(true);
            player.prepareAsync();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void encapsulatedOrbit(IjkTrackInfo[] mtInfo) {
        audioList = new ArrayList<>();
        if (mtInfo != null && mtInfo.length > 0) {
            /**添加默认选项*/
            for (int i = 0; i < mtInfo.length; i++) {
                IjkTrackInfo info = mtInfo[i];
                if (null == info) continue;
                if (info.getTrackType() == ITrackInfo.MEDIA_TRACK_TYPE_AUDIO) {
                    TrackBean tb = new TrackBean();
                    tb.setIndex(i);
//                    tb.setAudioName(info.getLanguage());
                    audioList.add(tb);
                }
            }
            try {
                if (!(audioList.size() > 0)) {
                    origLyrics.setFocusable(false);
                    origLyrics.setImageResource(R.drawable.music_channel_sel);
                } else {
                    origLyrics.setFocusable(true);
//                    player.setSelectTrack(audioList.get(0).getIndex());
                    player.selectTrack(audioList.get(0).getIndex());
                    audioSelIndex = 0;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    @Override
    protected void onPause() {
        super.onPause();
        if (player != null)
            player.pause();
    }

    private void hideSeekbar() {
        if (player != null) {
            if (player.isPlaying()) {
                playerControlBottomLayout.setVisibility(View.GONE);
                btn_play_pause.setVisibility(View.GONE);
                recycler.setVisibility(View.GONE);
            }
        }
    }

    private void showSeekbar() {
        playerControlBottomLayout.setVisibility(View.VISIBLE);
        if (player != null) {
            if (!player.isPlaying()) {
                btn_play_pause.setVisibility(View.VISIBLE);
            }
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            setResult(10001, new Intent());
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (timerTask != null) {
            timerTask.cancel();
            timerTask = null;
        }
        if (load_img != null) {
            load_img.clearAnimation();
        }
    }

    private boolean isTimerTask = false;

    protected void exit() {
//        mHandler.removeCallbacksAndMessages(null);
        isTimerTask = true;
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (timerTask != null) {
            timerTask.cancel();
            timerTask = null;
        }
        playerDestory();
        setResult(10001, new Intent());
        finish();
        overridePendingTransition(0, 0);
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        player.setDisplay(mPlayerView.getHolder());
        player.start();
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.control_btn:
                try {
                    if (updateProgressBar != null && updateProgressBar.getVisibility() == View.VISIBLE) {
                        updateProgressBar.setVisibility(View.GONE);
                    }
                    if (player.isPlaying()) {
                        player.pause();
                        paly_btn.setImageResource(R.drawable.player_control_pause_sel);
                        btn_play_pause.setImageResource(R.mipmap.mediacontroller_play);
                        btn_play_pause.setVisibility(View.VISIBLE);
                    } else {
                        player.start();
                        paly_btn.setImageResource(R.drawable.player_control_playing_sel);
                        btn_play_pause.setImageResource(R.mipmap.mediacontroller_pause);
//                        mHandler.removeCallbacksAndMessages(null);
//                        mHandler.sendEmptyMessage(HIDE);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case R.id.forward_left:
                //快退处理
                long pos = player.getCurrentPosition();
                player.seekTo(pos - 5000);
                break;
            case R.id.forward_right:
                //快进处理
                long pos1 = player.getCurrentPosition();
                player.seekTo(pos1 + 5000);
                break;
            case R.id.music_list:
                //目前不清楚功能，应该是列表选择
                if (recycler.getVisibility() == View.VISIBLE) {
                    recycler.setVisibility(View.GONE);
                } else {
                    recycler.setVisibility(View.VISIBLE);
                    isFocus = true;
                }
                break;
            case R.id.play_mode:
                //修改播放模式，当前总共三种播放模式，循环列表，单曲循环，随机列表播放<可能会出现重复播放>
                PLAY_MODE++;
                switch (PLAY_MODE) {
                    case 1:
                        playMode.setImageResource(R.drawable.play_mode_sel);
                        break;
                    case 2:
                        playMode.setImageResource(R.drawable.play_mode_sel1);
                        break;
                    case 3:
                        playMode.setImageResource(R.drawable.play_mode_sel2);
                        break;
                    default:
                        PLAY_MODE = 1;
                        playMode.setImageResource(R.drawable.play_mode_sel);

                        break;
                }
                break;
            case R.id.music_replay:
                //当前歌曲重新开始播放
                player.seekTo(0);
                break;
            case R.id.music_next:
                //先判断播放模式，再根据模式切换到下一首
                switchMusic();
                break;
            case R.id.orig_lyrics:
                //麦克风选择处理
                if (audioList != null && audioList.size() >= 2) {
                    audioSelIndex++;
                    if (audioSelIndex == 1) {
                        origLyrics.setImageResource(R.drawable.music_channel_sel1);
                        player.selectTrack(audioList.get(audioSelIndex).getIndex());
//                        player.setSelectTrack(audioList.get(audioSelIndex).getIndex());
                    } else {
                        audioSelIndex = 0;
                        origLyrics.setImageResource(R.drawable.music_channel_sel);
                        player.selectTrack(audioList.get(audioSelIndex).getIndex());
//                        player.setSelectTrack(audioList.get(audioSelIndex).getIndex());
                    }
                } else {
                    ToastUtils.showShortToastSafe("此歌曲不支持伴唱！");
                }
                break;
            case R.id.music_collect:
                //提交收藏接口
                if (isCollect) {
                    isCollect = false;
                } else {
                    isCollect = true;
                }
                musicCollect.setSelected(false);
//                ToastUtils.showShortToastSafe("暂未开放");
                break;
            default:
                break;
        }
    }

    private boolean isCollect = false;

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        try {
            long pos = seekBar.getProgress();
            player.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "seek-at-start", pos);
            String time = StringUtils.generateTime(player.getCurrentPosition());
            tv_time_current.setText(time);
            mHandler.sendMessageDelayed(mHandler.obtainMessage(HIDE), timeout);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private boolean isFocus = false, isDel = false;
    private int delPos = 0;

    @Override
    public void onGlobalLayout() {
        if (videoBeanList != null && videoBeanList.size() > 0)
            if (recycler.getVisibility() == View.VISIBLE && isFocus) {
                isFocus = false;
                if (isDel) {
                    isDel = false;
                    if (videoBeanList.size() > 0) {
                        if (videoBeanList.size() > delPos)
                            recycler.getLayoutManager().findViewByPosition(delPos).findViewById(R.id.delete_m).requestFocus();
                        else {
                            recycler.getLayoutManager().findViewByPosition(videoBeanList.size() - 1).findViewById(R.id.delete_m).requestFocus();
                        }
                    }
                } else
                    recycler.getLayoutManager().findViewByPosition(startPosition).findViewById(R.id.start_play).requestFocus();
            }
    }

    @Override
    public void onRightFocusChange(View view, boolean flag, int pos) {
        if (flag) {
            recycler.smoothToCenter(pos);
        }
    }

    @Override
    public void onRightClick(View view, int pos) {
        switch (view.getId()) {
            case R.id.delete_m:
//                Observable<JsonObject> ob = SytRetrofit.getInstance().postDel(videoBeanList.get(pos).getSongId(), "29052743511", "HW");
//                ob.subscribeOn(Schedulers.io())
//                        .observeOn(AndroidSchedulers.mainThread())
//                        .subscribe(new Observer<JsonObject>() {
//                            @Override
//                            public void onSubscribe(Disposable d) {
//
//                            }
//
//                            @Override
//                            public void onNext(JsonObject jsonObject) {
//                                Log.d("sss", jsonObject.toString());
//                            }
//
//                            @Override
//                            public void onError(Throwable e) {
//                                e.printStackTrace();
//                            }
//
//                            @Override
//                            public void onComplete() {
//
//                            }
//                        });
                videoBeanList.remove(pos);
                isFocus = true;
                isDel = true;
                delPos = pos;
                listAdapter.setData(videoBeanList);
                if (videoBeanList.size() == 0) {
                    recycler.setVisibility(View.GONE);
                }

                break;
            case R.id.start_play:
                startPosition = pos;
                if (PLAY_MODE == 1) {
                    nextPosition++;
                    if (nextPosition >= videoBeanList.size()) {
                        nextPosition = 0;
                    }
                } else if (PLAY_MODE == 3) {
                    nextPosition = new Random().nextInt(videoBeanList.size());
                }
                String path = videoBeanList.get(startPosition).getSongRes();
                mName = videoBeanList.get(startPosition).getSongName();
                nextNameStr = videoBeanList.get(nextPosition).getSongName();
                authName = videoBeanList.get(startPosition).getSinger();
                playerDestory();
                setSurfaceGone();
                player.setDisplay(mPlayerView.getHolder());
                openVideo(path);
                break;
        }
    }

    private void switchMusic() {
        if (videoBeanList != null && videoBeanList.size() > 0) {
            startPosition = nextPosition;
            if (PLAY_MODE == 1) {
                nextPosition++;
                if (nextPosition >= videoBeanList.size()) {
                    nextPosition = 0;
                }
            } else if (PLAY_MODE == 3) {
                nextPosition = new Random().nextInt(videoBeanList.size());
            }
            if (videoBeanList.size() == 1) startPosition = 0;
//            String path = videoBeanList.get(startPosition).getSongRes();
            String path = allPath.get(startPosition);
            mName = videoBeanList.get(startPosition).getSongName();
            nextNameStr = videoBeanList.get(nextPosition).getSongName();
            authName = videoBeanList.get(startPosition).getSinger();
            playerDestory();
            setSurfaceGone();
            if (player == null) {
                player = new IjkMediaPlayer();
                player.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "enable-accurate-seek", 1);
            }
            player.setDisplay(mPlayerView.getHolder());
            openVideo(path);
        }
    }

    private long mExitTime;
    private boolean limitOperate = false;

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        switch (event.getAction()) {
            case KeyEvent.ACTION_DOWN:
                switch (event.getKeyCode()) {
//                    case KeyEvent.KEYCODE_ENTER:
//                    case KeyEvent.KEYCODE_DPAD_CENTER:
//                        if (!limitOperate) return true;
//                        mHandler.sendEmptyMessage(SHOW);
//                        View view = getCurrentFocus();
//                        if (seek_to_time.getVisibility() == View.VISIBLE) {
//                            seek_to_time.setVisibility(View.GONE);
//                        }
//                        if (updateProgressBar != null && updateProgressBar.getVisibility() == View.VISIBLE) {
//                            updateProgressBar.setVisibility(View.GONE);
//                        }
//                        if (view == null || view.getId() == R.id.seekBar || view.getId() == R.id.btn_play_pause) {
//                            if (player != null) {
//                                if (player.isPlaying()) {
//                                    player.stop();
//                                    paly_btn.setImageResource(R.drawable.player_control_pause_sel);
//                                    btn_play_pause.setImageResource(R.mipmap.mediacontroller_play);
//                                    btn_play_pause.setVisibility(View.VISIBLE);
//                                } else {
//                                    try {
//                                        player.start();
//                                        paly_btn.setImageResource(R.drawable.player_control_playing_sel);
//                                        btn_play_pause.setImageResource(R.mipmap.mediacontroller_pause);
//                                        mHandler.removeCallbacksAndMessages(null);
//                                        mHandler.sendEmptyMessage(HIDE);
//                                    } catch (Exception e) {
//                                        e.printStackTrace();
//                                    }
//                                }
//                            }
//                        }
//                        break;
//                    case KeyEvent.KEYCODE_DPAD_RIGHT:
//                        if (!limitOperate) return true;
////                        mHandler.sendEmptyMessage(SHOW);
//                        if (playerControlBottomLayout.getVisibility() == View.VISIBLE) {
//                            View focusViewRight = getCurrentFocus();
//                            if (focusViewRight != null)
//                                if (focusViewRight.getId() == R.id.seekBar) {
//                                    if (player != null) {
//                                        player.seekto(player.getCurrentPosition() + 60000);
//                                    }
//                                    return true;
//                                }
//                        } else {
//                            if (player != null) {
//                                seekTo(player.getCurrentPosition(), 5000);
//                                player.seekto(player.getCurrentPosition() + 5000);
//                            }
//                            return true;
//                        }
//                        hideBottomLayout();
//                        break;
//                    case KeyEvent.KEYCODE_DPAD_LEFT:
//                        if (!limitOperate) return true;
////                        mHandler.sendEmptyMessage(SHOW);
//                        if (playerControlBottomLayout.getVisibility() == View.VISIBLE) {
//                            View focusViewLeft = getCurrentFocus();
//                            if (focusViewLeft != null)
//                                if (focusViewLeft.getId() == R.id.seekBar) {
//                                    if (player != null) {
//                                        player.seekto(player.getCurrentPosition() - 60000);
//                                    }
//                                    return true;
//                                }
//                        } else {
//                            if (player != null) {
//                                seekTo(player.getCurrentPosition(), -5000);
//                                player.seekto(player.getCurrentPosition() - 5000);
//                            }
//                            return true;
//                        }
//                        hideBottomLayout();
//                        break;
                    case KeyEvent.KEYCODE_DPAD_DOWN:
                        boolean isflag = false;
                        if (!limitOperate) return true;
                        mHandler.sendEmptyMessage(SEEK_VIEW_HIDE);
                        mHandler.sendEmptyMessage(SHOW);
                        if (playerControlBottomLayout.getVisibility() == View.VISIBLE) {
                            View focusViewDown = getCurrentFocus();
                            if (focusViewDown != null)
                                if (focusViewDown.getId() == R.id.seekBar || focusViewDown.getId() == R.id.forward_left) {
                                    paly_btn.requestFocus();
                                    isflag = true;
                                } else if (focusViewDown.getId() == R.id.item) {
                                    paly_btn.requestFocus();
                                    isflag = true;
                                }
                        }
                        /**0925 去掉 改为下面*/
                        hideBottomLayout();
                        return isflag;
                    case KeyEvent.KEYCODE_DPAD_UP:
                        boolean flag = false;
                        if (playerControlBottomLayout.getVisibility() == View.VISIBLE) {
                            View focusViewUp = getCurrentFocus();
                            if (focusViewUp != null)
                                if (focusViewUp.getId() == R.id.control_btn) {
                                    seekBar.requestFocus();
                                    flag = true;
                                }
                        }
                        hideBottomLayout();
                        return flag;
                    case KeyEvent.KEYCODE_BACK:
                        if (recycler.getVisibility() == View.VISIBLE) {
                            recycler.setVisibility(View.GONE);
                        }
                        if ((System.currentTimeMillis() - mExitTime) > 2000) {
                            Toast.makeText(this, "再按一次退出播放", Toast.LENGTH_SHORT).show();
                            mExitTime = System.currentTimeMillis();
                            return true;
                        } else {
                            exit();
                        }
                        return true;
                    case KeyEvent.KEYCODE_HOME:
                        return true;
                }
                break;
        }
        return super.dispatchKeyEvent(event);
    }

    private void setSurfaceGone() {
        if (mPlayerView != null) {
            mPlayerView.setVisibility(View.GONE);
        }
    }

    private void playerDestory() {
        if (player != null) {
            player.stop();
            player.release();
            player = null;
        }
    }

    private class MyHandler extends Handler {
        private WeakReference<IjkVideoActivity> reference;

        public MyHandler(IjkVideoActivity reference) {
            this.reference = new WeakReference<IjkVideoActivity>(reference);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case HIDE:
                    hideSeekbar();
                    break;
                case SHOW:
                    showSeekbar();
                    break;
                case FINISH:
                    setResult(10001, new Intent());
                    finish();
                    break;
                case ENABLE_SEEK:
                    break;
                case ENABLE_PLAY:
                    try {
                        player.start();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case SEEK_VIEW_HIDE:
                    hideSeekText();
                    break;
            }
        }
    }

    private void hideSeekText() {
        if (seek_to_time != null && seek_to_time.getVisibility() == View.VISIBLE) {
            seek_to_time.setVisibility(View.GONE);
        }
    }

    private void hideBottomLayout() {
        if (playerControlBottomLayout.getVisibility() == View.VISIBLE) {
            mHandler.removeCallbacksAndMessages(null);
            mHandler.sendMessageDelayed(mHandler.obtainMessage(HIDE), timeout);
        }
    }
}
